package com.quicksand.push;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


public class SpringWebSocketHandler extends TextWebSocketHandler {
    private static final String EQUIPMENT_NAME = "equipment";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final ArrayList<WebSocketSession> users;//这个会出现性能问题，最好用Map来存储，key用userid
    private static Logger logger = Logger.getLogger(SpringWebSocketHandler.class);

    static {
        users = new ArrayList<WebSocketSession>();
    }

    public SpringWebSocketHandler() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("connect to the websocket success......当前数量:" + users.size());
        users.add(session);
        //这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
        //TextMessage returnMessage = new TextMessage("你将收到的离线");
        //session.sendMessage(returnMessage);
    }

    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.debug("websocket connection closed......");
        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        System.out.println("用户" + username + "已退出！");
        users.remove(session);
        System.out.println("剩余在线用户" + users.size());
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息" + message.getPayload());
//        Date now=new Date();
//        this.sendMessageToUsers(new TextMessage("全部回复"+sdf.format(now)));
//        System.out.println(this);
        String newMsg = message.getPayload();
        if (!"".equals(newMsg)) {
            if ("getAllEquipments".equals(newMsg)) {//命令  获取所有设备
                try {
                    session.sendMessage(new TextMessage("在线设备:"+String.valueOf(this.getAllEquipments().size())));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
            } else {//冒号:  向谁:发送消息
                String[] msglist = newMsg.split(":");
                if (msglist.length == 2) {
                    String sliceStr = msglist[0].length()>=9?msglist[0].substring(0, 9):msglist[0];
                    if (sliceStr.equals(EQUIPMENT_NAME)) {//用户向设备发送命令
                        this.sendMessageToUser(msglist[0], new TextMessage(msglist[1]));
                    }else{
                        this.sendMessageToUser(msglist[0], new TextMessage(msglist[1]));
                    }
                }
            }


        }


        super.handleTextMessage(session, message);
    }

    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.debug("websocket connection closed......");
        users.remove(session);
    }

    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 返回所有设备列表
     */
    public ArrayList<WebSocketSession> getAllEquipments() {
        ArrayList<WebSocketSession> usersTemp = new ArrayList<WebSocketSession>();
        for (WebSocketSession item : this.users) {
            if (item.isOpen()) {
                String username = (String) item.getAttributes().get("WEBSOCKET_USERNAME");
                if(username.length()>=9){
                    String sliceStr = username.substring(0, 9);
                    if (sliceStr.equals(EQUIPMENT_NAME)) {//匹配名字,是一个设备
                        usersTemp.add(item);
                    }
                }

            }
        }
        return usersTemp;
    }



}